require( "gip")
require( "util")

local tmpDir = "/home/wzp/dtools/gip/tools/tmp/"

local asCode0_0 = [[
package
{
    import flash.display.Bitmap;
    import flash.display.BitmapData;
    import flash.geom.Point;
    import flash.display.Sprite;

    public class %s extends Sprite
    {
        public var offset:Vector.<Point> = new Vector.<Point>(%d,true);
        public var images:Vector.<BitmapData> = new Vector.<BitmapData>(%d,true);

        public function %s(){
]]

local asCode0_1 = [[
            offset[%d] = new Point( %d, %d);
            images[%d] = Bitmap(new %s).bitmapData;

]]

local asCode0_2 = [[
        }
]]

local asCode1 = [[
        [Embed(source="%s", mimeType="image/png", compression="true", quality="%d")]
        private const %s:Class;

]]

local asCode1_0 = [[
        [Embed(source="%s", mimeType="image/jpeg")]
        private const %s:Class;

]]

local asCode2 = [[
    }
}
]]

function genSwf( images, imageskeys, classname, cmpQuality, isJpeg)
    cmpQuality = cmpQuality or 70
    os.execute( "rm -rf " .. tmpDir .. "/*.*")
    local asFilename = tmpDir .. classname .. ".as"
    gip.createParentDir( asFilename)
    local asFile = io.open( asFilename, "wt")
    if asFile == nil then
        print( "gen as3 code file : " .. asFilename .. "failed")
        return ""
    end

    local n = table.getn( imageskeys)
    local s0 = string.format( asCode0_0, classname, n, n, classname) 
    asFile:write( s0)

    local index = 1
    for _, k in ipairs( imageskeys) do
        local v = images[k]
        local suffix = numbertofixstr( index, 4)
        asFile:write( string.format( asCode0_1, 
            index - 1, v.offsetX, v.offsetY,
            index - 1, "Img" ..suffix))

        index = index + 1
    end
    asFile:write( asCode0_2)

    index = 1
    for _, k in ipairs( imageskeys) do
        local v = images[k]
       
        local suffix = numbertofixstr( index, 4)
        local imgFile
        if isJpeg then 
            imgFile = suffix .. ".jpg"
        else
            imgFile = suffix .. ".png"
        end

        local imgClass = "Img" .. suffix
        if isJpeg then
            asFile:write( string.format( asCode1_0, imgFile, imgClass))
        else
            asFile:write( string.format( asCode1, imgFile,
                cmpQuality, imgClass))
        end

        v.image.save( tmpDir .. imgFile)

        index = index + 1
    end
    asFile:write( asCode2)
    asFile:close()

    os.execute( "mxmlc -static-link-runtime-shared-libraries " .. asFilename)
    return tmpDir .. classname .. ".swf"
end

